package com.atguigu.c_designed.m3beheviorModel.b6Mediator;

public class MediatorClient {
    public static void main(String[] args) {
        ChatMediator chatMediator = new ServerChatMediator();
        new ChatRoom().setMediator(chatMediator);

        User user = new User(chatMediator,"Tom");
        user.sendMsg("大家好，我是Tom");
        User user2 = new User(chatMediator,"Jerry");
        user2.sendMsg("大家好，我是Jerry");

    }
}

class User {
    ChatMediator chatMediator;
    private String name;

    public User(ChatMediator chatMediator, String name) {
        this.chatMediator = chatMediator;
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void sendMsg(String msg) {
        chatMediator.sendToChatRoom(this,msg);
    }
}

class ChatRoom {
    private ChatMediator mediator;

    public void setMediator(ChatMediator mediator) {
        this.mediator = mediator;
        this.mediator.setRoom(this);
    }
    public void showMsg(User user,String msg) {
        System.out.println("[" + user.getName() + "] :" + msg);
    }
}


abstract class ChatMediator{
    protected ChatRoom room;

    public void setRoom(ChatRoom room) {
        this.room = room;
    }
    public abstract void sendToChatRoom(User user,String msg);
}

class ServerChatMediator extends ChatMediator{
    @Override
    public void sendToChatRoom(User user, String msg) {
        this.room.showMsg(user,msg);
    }
}